package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;

import com.ruoyi.common.core.domain.entity.SysCorp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.dao.service.BaseAppDAO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.dao.SysDeptDAO;
import com.ruoyi.system.dao.SysRoleDAO;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService
{
    @Autowired
    private SysDeptDAO deptDAO;

    @Autowired
    private SysRoleDAO roleDAO;
    
    @Autowired
    private BaseAppDAO baseDAO;




    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
//    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
    	
    	Specification<SysDept> specification = (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			predicateList.add(criteriaBuilder.equal(root.get("delFlag"), "0"));
			
			if (!StringUtils.isNull(dept.getDeptId())) {
				predicateList.add(criteriaBuilder.equal(root.get("deptId"), dept.getDeptId()));
			}
			if (!StringUtils.isNull(dept.getParentId())) {
				predicateList.add(criteriaBuilder.equal(root.get("parentId"), dept.getParentId()));
			}
			if (!StringUtils.isEmpty(dept.getDeptName())) {
				predicateList.add(criteriaBuilder.equal(root.get("deptName"), dept.getDeptName()));
			}
			if (!StringUtils.isEmpty(dept.getStatus())) {
				predicateList.add(criteriaBuilder.equal(root.get("status"), dept.getStatus()));
			}

            if (!StringUtils.isEmpty(dept.getPkCorp())) {
                predicateList.add(criteriaBuilder.equal(root.get("pkCorp"), dept.getPkCorp()));
            }
			Predicate[] p = new Predicate[predicateList.size()];
			return criteriaBuilder.and(predicateList.toArray(p));
		};


		return deptDAO.findAll(specification);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnvos = new ArrayList<SysDept>();//要返回的数据，没有父id的数据为第一层级数据
        if (StringUtils.isNotEmpty(depts)) {
            HashMap<String, List<SysDept>> childrens = new HashMap<String, List<SysDept>>();//把所有相同父id的数据放在一起
            SysDept dept = null;
            for (int i = 0; i < depts.size(); i++) {
                dept = depts.get(i);
                if (StringUtils.isEmpty(dept.getParentId())) {
                    returnvos.add(dept);
                } else {
                    if (!childrens.containsKey(dept.getParentId())) {
                        childrens.put(dept.getParentId(), new ArrayList<SysDept>());
                    }
                    childrens.get(dept.getParentId()).add(dept);
                }
            }

            if (StringUtils.isNotEmpty(childrens)) {
                findDomainChildens(returnvos, childrens);
            }
        }
        return returnvos;
    }

    private void findDomainChildens(List<SysDept> depts, HashMap<String, List<SysDept>> childrens) {
        if (StringUtils.isNotEmpty(depts) && StringUtils.isNotEmpty(childrens)) {
            for (SysDept dept : depts) {
                if (childrens.containsKey(dept.getDeptId())) {
                    dept.setChildren(childrens.get(dept.getDeptId()));
                    childrens.remove(dept.getDeptId());
                    findDomainChildens(dept.getChildren(), childrens);
                }
            }
        }
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(String roleId)
    {
        SysRole role = roleDAO.findById(roleId).orElse(null);
        return selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }
    
    
    private List<Long> selectDeptListByRoleId(String roleId,boolean deptCheckStrictly){
    	String querysql = " select d.dept_id from sys_dept d left join sys_role_dept rd on d.dept_id = rd.dept_id ";
    	querysql += " where rd.role_id ="+roleId;
    	if(deptCheckStrictly){
    		querysql += " and d.dept_id not in (select d.parent_id from sys_dept d inner join sys_role_dept rd on d.dept_id = rd.dept_id and rd.role_id = "+roleId;
    	}
    	querysql += " order by d.parent_id, d.order_num ";
    	
    	return baseDAO.createNativeQuery(querysql);
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(String deptId)
    {
        return deptDAO.findById(deptId).orElse(null);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(String deptId)
    {
        return (int) deptDAO.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(String deptId)
    {
        int result = (int)deptDAO.selectChildCountByParentId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(String deptId)
    {
    	int result = deptDAO.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept)
    {
        String deptId = StringUtils.isNull(dept.getDeptId()) ? "" : dept.getDeptId();
        SysDept info = deptDAO.findTop1findByDeptNameAndParentId(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && !info.getDeptId().equals(deptId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     * 
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(String deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUsername()))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDept(SysDept dept)
    {
        SysDept info = deptDAO.findById(dept.getParentId()).orElse(null);
        if(StringUtils.isNotNull(info)){
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
            {
                throw new ServiceException("部门停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        }
        deptDAO.save(dept);
        return 1;
    }

    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptDAO.findById(dept.getParentId()).orElse(null);
        SysDept oldDept = deptDAO.findById(dept.getDeptId()).orElse(null);
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        deptDAO.save(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return 1;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        String[] deptIds = Convert.toStrArray(ancestors);
        
        deptDAO.updateDeptStatusNormal(Arrays.asList(deptIds));
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(String deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptDAO.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptDAO.saveAll(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDeptById(String deptId)
    {
    	deptDAO.deleteById(deptId);
        return 1;
    }

}
